<?php
/**
 * Created by PhpStorm.
 * User: caviar
 * Date: 2019/9/19
 * Time: 15:04
 */

namespace app\http\middleware;

use app\lib\exception\ParameterException;
use think\Exception;

/**
 * Class SignVerify
 * @package app\http\middleware
 * Sign 验证中间件
 */
class SignVerify
{
    //
    private $params;

    /**
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle($request, \Closure $next)
    {
        $this->params = $request->param();

        if (config('projectConfig.signVerify') == true)
        {
            if (!isset($this->params['sign']))
            {
                throw new ParameterException('Sign Not Null!');
            }
            if ($this->params['sign'] != $this->createSign($this->params))
            {
                throw new ParameterException('Sign is Atypical!');
            }
        }
        return $next($request);
    }

    private function createSign($params)
    {
        unset($params['sign']);
        $string = '';
        foreach ($params as $key=>$value)
        {
            if (!empty($value))
            {
                if(!preg_match('/[\x{4e00}-\x{9fa5}]/u',$value))  {
                    $string .= $key.'='.$value.'&';
                }
            }
        }
        return '111';
//        return $string;
    }




}